package com.jzoom.zoom.admin.models;

import com.jzoom.zoom.cache.annotations.Cache;
import com.jzoom.zoom.cache.annotations.CacheRemove;
import com.jzoom.zoom.common.annotations.Inject;
import com.jzoom.zoom.dao.Ar;
import com.jzoom.zoom.dao.Dao;
import com.jzoom.zoom.token.hex.ClientToken;
import com.jzoom.zoom.web.action.ActionContext;
import com.jzoom.zoom.web.exception.StatusException;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class AuthService {
	private static final String[] HAS_VALUE_ARR = new String[]{"del", "get", "put"};
    private static final String[] NO_VALUE_ARR = new String[]{"index", "add", "list", "edit", "export"};

	private static final Log log = LogFactory.getLog(AuthService.class);

	@Inject(value = "admin")
	private Dao dao;
	
	public AuthService() {
	}

    @CacheRemove(format = "modules:%s")
    public void clearCache(ClientToken clientToken) {

    }

	/**
	 * 获取本人对应能访问的所有模块id数组
	 * @param clientToken
	 * @return
	 */
	@Cache(format="modules:%s")
	public String[] getAuthModuleIds(ClientToken clientToken) {
		String mods = dao.table("sys_user").where("sys_user.id", clientToken.getId())
                .join("sys_role",
                        "sys_role.id=sys_user.rl_id")
                .getValue("mods", String.class);
		if (mods == null) {
			throw new StatusException.AuthException();
		}
		String[] parts = mods.split(",");
		return parts;
	}

    //两个就好了，足以确定
    @Cache(format = "module_url_id:%s:%s")
    public String getVisitModuleId(String userId,
                                   String actionPath,
                                   String servletPath) {
        String id;
        if (servletPath.startsWith("/")) {
            servletPath = servletPath.substring(1);
        }
        String url = getUrl(servletPath);
        Ar ar = dao.table("sys_mod").where("url", url);
        if (!url.equals(servletPath)) {
            ar.orWhere("url", servletPath);
        }
        ar.orWhere("url", actionPath);
        id = ar.getValue("id", String.class);

        return id;
    }

    /**
     * 获取本次访问的模块id
     *
     * @return
     */
    //
    //String key = String.format("module_url_id:%s",path);
    public String getVisitModuleId(ActionContext context, String userId) {
        String servletPath = context.getRequest().getServletPath();
        String actionPath = context.getAction().getPath();

        return getVisitModuleId(userId, actionPath, servletPath);
    }

    public String[] checkAuth(ClientToken clientToken, ActionContext context, String userId) {

		String[] authModuleIds = getAuthModuleIds(clientToken);
        String moduleId = getVisitModuleId(context, userId);
		
		if (ArrayUtils.indexOf(authModuleIds, moduleId) < 0) {
			throw new StatusException.AuthException();
		}
		return authModuleIds;
	}


	// 最后一个元素必须是 NO_VALUE_ARR 里面的,如果没有参数
	// 如果是 module/index module/add module/get/1 module/put/1 module/delete/1
	// id=>11-11
	private String getUrl(String path) {
		// 如果是一般的增删查改，则使用模糊匹配就行了
		String[] parts = path.split("\\/");
		if (parts.length == 2) {
			// module/add 或者 module/index module/edit
			if (ArrayUtils.contains(NO_VALUE_ARR, parts[1])) {
				return parts[0] + "/index";
			}
		}
		if (parts.length == 3) {
			// ds/module/add或者ds/module/index
			// module/get/1 等
			if (ArrayUtils.contains(HAS_VALUE_ARR, parts[1])) {
				return parts[0] + "/index";
			}
			//检查下是否是index/add/list
			if (ArrayUtils.contains(NO_VALUE_ARR, parts[2])) {
				return parts[0] + "/" + parts[1] + "/index";
			}
		}
		if (parts.length == 4) {
			if (ArrayUtils.contains(HAS_VALUE_ARR, parts[2])) {
				return parts[0] + "/" + parts[1] + "/index";
			}
		}
		return path;
	}

}
